﻿namespace IBTrader.Indicator.CandleStick
{
    using IBTrader.Modules.Read;
    using IBTrader.Charts;
    using System;
    using System.Linq;

    class HeikinAshi : Base // CandleStick
    {
        private Item last;
        public HeikinAshi(Worker worker, int seconds = 5*60) : base(worker, seconds) { }
        public override void Add(object sender, Line line)
        {
            base.Add(sender, line);
            (item as HeikinAshiItem).Add(line, last);
            last = item;
        }
        protected override Item NewItem()
        {
            return new HeikinAshiItem();
        }
        public class HeikinAshiItem : Item
        {
            protected internal override void Add(Line line)
            {
                // do nothing;
            }
            internal void Add(Line line, Item last)
            {
                if (OpenLine == null)
                {
                    //Symbol = line.Symbol;
                    DateTime = line.DateTime;
                    High = Low = Open = Close = Price = line.Price;
                    OpenLine = CloseLine = line;

                    if (last != null)
                    {
                        Open = (last.Open + last.Close) / 2;
                        OpenLine = NewLine(OpenLine, Open);
                    }
                }
                else
                {
                    Close = (Open + High + Low + line.Price) / 4;
                    CloseLine = NewLine(line, Close);
                    High = new [] { High, Open, Close }.Max();
                    Low = new[] { Low, Open, Close }.Max();
                }
            }
        }
    }
}